package com.jorado.apollo.service;

import com.google.common.base.Joiner;
import com.google.common.reflect.TypeToken;
import com.jorado.apollo.dto.AppDTO;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.lang.reflect.Type;
import java.util.List;

public class AppApiService extends AbstractApiService {

    private static final Type OPEN_APP_DTO_LIST_TYPE = new TypeToken<List<AppDTO>>() {
    }.getType();

    public AppApiService(CloseableHttpClient client, String baseUrl) {
        super(client, baseUrl);
    }

    public List<AppDTO> getAppsInfo(List<String> appIds) {
        String path = "apps";

        if (appIds != null && !appIds.isEmpty()) {
            String param = Joiner.on(",").join(appIds);
            path = String.format("apps?appIds=%s", escapeParam(param));
        }

        try (CloseableHttpResponse response = get(path)) {
            return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_APP_DTO_LIST_TYPE);
        } catch (Throwable ex) {
            throw new RuntimeException(String.format("Load app information for appIds: %s failed", appIds), ex);
        }
    }
}
